<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    	$usuario = Zend_Auth::getInstance()->getIdentity();
    	$this->view->usuario = $usuario;
    	
//     	Zend_Debug::dump($usuario);exit;
    	
    }

    public function indexAction()
    {
	    if ( !Zend_Auth::getInstance()->hasIdentity() ) {
	        $this->_redirect('/login');
	    }
	    $usuario = Zend_Auth::getInstance()->getIdentity();
	    $this->view->usuario = $usuario;
	    
	    Zend_Debug::dump($usuario);
	    
    }

    public function loginAction()
    {
    	$this->view->headTitle("Login | EJC BR");
    	$this->view->headLink()->appendStylesheet('/css/login/login.css','all');
    	$this->view->headScript()->appendFile('/js/login/login.js');
    	$this->view->logado = false;

    	
    	$this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
    	$this->view->messages = $this->_flashMessenger->getMessages();
    	$form = new Application_Form_Login();
    	$this->view->form = $form;
    	
    	//Verifica se existem dados de POST
    	if ( $this->getRequest()->isPost() ) {
    		$this->_helper->layout()->disableLayout();
    		$this->_helper->viewRenderer->setNoRender(true);
    		
    		$data = $this->getRequest()->getPost();
    		
    		//Formulário corretamente preenchido?
    		if ( $form->isValid($data) ) {
    			$login = $form->getValue('login');
    			$senha = $form->getValue('senha');
    	
    			try {
                    Application_Model_Auth::login($login, $senha);
                    //Redireciona para o Controller protegido
                    $this->_redirect('/');
                } catch (Exception $e) {
                    //Dados inválidos
                    $this->_helper->FlashMessenger($e->getMessage());
                    $this->_redirect('/login');
                }
    		} else {
    			//Formulário preenchido de forma incorreta
    			$form->populate($data);
    		}
    	}
    }

    public function logoutAction()
    {
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender(true);
    	
        $auth = Zend_Auth::getInstance();
	    $auth->clearIdentity();
    	$this->_redirect('/login');
    }


}